<template>
  <view class="personal-center">
    <!-- 用户信息卡片 -->
    <UserInfoCard :user="user" :changeProfile="changeProfile" :changeInfo='changeInfo'/>

    <!-- 功能列表 -->
    <view class="function-list">
      <view class="function-item" v-for="item in functionList" :key="item.id" @click="handleFunctionClick(item)">
        <text class="icon">{{ item.icon }}</text>
        <text class="label">{{ item.label }}</text>
        <text class="arrow">></text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import {onShow} from '@dcloudio/uni-app'
import UserInfoCard from '@/components/UserInfoCard/UserInfoCard.vue';
import { baseUrl,checkToken } from '../../static/js/common';
// 用户信息
const user = ref({
  avatar: '/static/logo.png',
  nickname: '未登录',
  bio: '这个人很懒，什么都没有写',
  isLogin:false
});

// 功能列表
const functionList = ref([
  { id: 1, icon: '📝', label: '我的领养期望', path: '/pages/record/record' },
  { id: 2, icon: '📝️', label: '我的帖子', path: '/pages/record/record' }
]);

	function changeInfo(infoType){
		let title=''
		let pro=''
		if(infoType=='desc'){
			title='请填写修改的自我介绍'
			pro='请输入自我介绍'
		}else{
			title='请填写修改的用户名'
			pro='请输入用户名'
		}
		
		let token=localStorage.getItem("token")
		checkToken(token)
		let userStr=localStorage.getItem('userInfo')
		let userInfo=JSON.parse(userStr)
		uni.showModal({
		        title: title,
		        content: '',
		        editable:true,//是否显示输入框
				placeholderText:'请输入用户名',//输入框提示内容
		        confirmText: '确认',
		        cancelText: '取消',
		        success: (res) => {
		          if (res.confirm) {
		            console.log('输入的内容：', res.content);
					let params={id:userInfo.id}
					if(infoType=='desc'){
						params.desc=res.content
					}else if(infoType=='name'){
						params.username=res.content
					}
					let url=baseUrl+'/user/updateInfo'
					uni.request({
						url:url,
						method:'POST',
						header:{'Authorization':token},
						data:params,
						success:(res)=>{
							if(res.data.code==400){
								uni.showToast({
									title: res.data.msg,
									icon: 'fail'
								})
							}
							else if (res.data.code==200){
								uni.showToast({
								  title: '修改成功',
								  icon: 'success'
								});
								localStorage.setItem("userInfo",JSON.stringify(res.data.data))
								initUserInfo()
							}
						}
					})
		          }
		        } 
		      });
	}


	function changeProfile(){
		let userStr=localStorage.getItem('userInfo')
		if(userStr==null){
			uni.showToast({
				icon:'error',
				title:'请先登录'
			})
			return
		}
		let userInfo=JSON.parse(userStr)
		uni.chooseImage({
			success:(res)=> {
				user.value.avatar=res.tempFilePaths[0]
				let url=baseUrl+"/image/uploadImage"
				updateFile(url,res,userInfo,baseUrl)

			}
		})
	}


// 处理功能项点击事件
const handleFunctionClick = (item) => {
  sessionStorage.setItem("userRecordType",item.id)
  uni.navigateTo({
    url: item.path,
  });
};


function updateFile(url,res,userInfo,baseUrl){
	let token=localStorage.getItem("token")
	uni.uploadFile({
		url:url,
		method:'POST',
		header:{'Authorization':token},
		name:"file",
		filePath:res.tempFilePaths[0],
		success:updaloadRes=>{
			let params={'profile':JSON.parse(updaloadRes.data).data,'id':userInfo.id}
			let url=baseUrl+'/user/updateProfile'
			updateProfile(url,params)
		},
		fail(f) {
			uni.showToast({
				icon:'error',
				title:'上传失败,请检查网络'
			})
		}
	})
}

function  updateProfile(url,params){
	let token=localStorage.getItem("token")
	uni.request({
		url:url,
		data:params,
		header:{'Authorization':token},
		success:userDtoRes=>{
			if(userDtoRes.data.code==200){
				uni.showToast({
					icon:'success',
					title:userDtoRes.data.msg
				})
				localStorage.setItem("userInfo",JSON.stringify(userDtoRes.data.data))
			}
		}
	})
}

onShow(()=>{
	user.value={
	  avatar: '/static/logo.png',
	  nickname: '未登录',
	  bio: '这个人很懒，什么都没有写',
	  isLogin:false
	};
	initUserInfo()
})

function initUserInfo(){
	let userInfo=localStorage.getItem("userInfo")
	if(userInfo!=null){
		userInfo=JSON.parse(userInfo)
		if(userInfo.profilePath!='' && userInfo.profilePath!=null ){
			user.value.avatar=userInfo.profilePath
		}
		user.value.nickname=userInfo.username
		if(userInfo.desc!='' && userInfo.desc!=null){
			user.value.bio=userInfo.desc
		}
		user.value.isLogin=true
	}
	
}

</script>

<style lang="scss" scoped>
.personal-center {
  padding: 20px;

  .function-list {
    margin-top: 20px;

    .function-item {
      display: flex;
      align-items: center;
      padding: 15px;
      border-bottom: 1px solid #eee;

      .icon {
        margin-right: 10px;
      }

      .label {
        flex: 1;
        font-size: 16px;
      }

      .arrow {
        font-size: 14px;
        color: #999;
      }
    }
  }
}
</style>